<template>
  <div class="page-content">
    <div>
      <el-button @click="$router.push('/purchase/offline/create')" type="primary" icon="el-icon-plus">添加采购单</el-button>
    </div>
    <br />
    <table-search
      ref="tableSearch"
      title="采购单列表"
      selection
      :columns="columns"
      :api="getList"
      @selection-change="onSelectionChange"
    >
      <div slot="table-title" class="table-title">
        <el-button
          size="medium"
          type="primary"
          plain
          :disabled="!selection.length"
          @click="onExport"
        >导出所选列表{{selection.length ? `(${selection.length})` : ''}}</el-button>
      </div>

      <template #totalPrice="{ row }">
        <span class="red">{{ $util.formatAmount(row.totalPrice) }}</span>
      </template>
      <template #payState="{ row }">
        <div :class="{ green: row.payState === 4 }">
          <span>{{ payStateMap[row.payState] }}</span>
        </div>
      </template>

      <template #deliveryState="{ row }">
        <span :class="{ green: row.deliveryState === 3 }">
          {{deliveryStateMap[row.deliveryState]}}
        </span>
      </template>
      <template #cancelState="{ row }">
        <span :class="row.cancelState === 1 ? 'green' : 'red'">{{
          cancelStateMap[row.cancelState]
        }}</span>
      </template>

      <template #invoice="{ row }">
        <el-link type="primary" @click="onViewInvoice(row)">
          {{row.uploadInvoiceTime ? '查看发票' : '上传发票'}}
        </el-link>
      </template>

      <template #relateOrderIds="{ row }">
        <template v-if="!row.relateOrderIds">
          未关联
        </template>
        <el-popover
          v-else
          v-for="(text, index) in row.relateOrderIds.split(',')"
          :key="index"
          placement="top"
          trigger="hover"
          :content="text"
        >
          <el-tag
            slot="reference"
            size="mini"
            style="margin: 3px;max-width: 100%;overflow: hidden;text-overflow: ellipsis;"
          >
            {{text}}
          </el-tag>
        </el-popover>
      </template>

      <template #operate="{ row }">
        <el-link type="primary" @click="$router.push(`/purchase/offline/detail/${row.purchaseNo}`)">查看详情</el-link>
        <el-link
          v-if="checkShowEdit(row)"
          type="primary"
          @click="$router.push(`/purchase/offline/edit/${row.purchaseNo}`)"
        >编辑</el-link>

        <el-popconfirm
          v-if="checkShowDelivery(row)"
          title="确认采购单已发货？"
          @confirm="onDelivery(row)"
        >
          <el-link
            slot="reference"
            type="primary"
          >确认发货</el-link>
        </el-popconfirm>

        <el-popconfirm
          v-if="checkShowConfirmFinish(row)"
          title="确认完成采购单？"
          @confirm="onConfirmFinish(row)"
        >
          <el-link
            slot="reference"
            type="primary"
          >确认完成</el-link>
        </el-popconfirm>

        <el-link v-if="checkShowPay(row)" type="primary" @click="$router.push(`/purchase/offline/detail/${row.purchaseNo}?isApplyPay=1`)">申请付款</el-link>

        <el-popconfirm
          v-if="checkShowInvalid(row)"
          title="确认作废采购单？"
          @confirm="onInvalid(row)"
        >
          <el-link
            slot="reference"
            type="primary"
          >作废</el-link>
        </el-popconfirm>

        <el-link
          v-if="checkShowRelateOrder(row)"
          type="primary"
          @click="onRelateOrder(row)"
        >关联订单号</el-link>
      </template>
    </table-search>

    <el-dialog
      v-if="invoice.currentItem"
      title="发票"
      width="50%"
      :visible.sync="invoice.visible"
    >
      <div v-loading="invoice.uploadLoading">
        <div class="upload-box" v-if="!invoice.currentItem.uploadInvoiceTime">
          <el-upload
            style="margin-bottom: 100px"
            drag
            multiple
            action=""
            :http-request="uploadInvoice"
            :show-file-list="false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将发票拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </div>
        <div class="upload-box" v-else>
          <div class="download-box">
            <div class="title">
              <i class="el-icon-s-order yellow icon"></i>发票
            </div>
            <span class="text"
              >上传成功：{{ invoice.currentItem.createTime | formatDate }}</span
            >
          </div>
          <div class="btn-box">
            <el-upload
              style="display: inline-block; margin: 0 10px"
              name="file"
              action=""
              :show-file-list="false"
              :http-request="uploadInvoice"
            >
              <el-button type="primary">重新上传</el-button>
            </el-upload>
            <el-button type="primary" @click="onDownloadInvoice">下载</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TableSearch from '@/components/TableSearch/TableSearch';
import { createTableColumns } from '@/components/TableSearch/utils';

import { payStateMap, deliveryStateMap, payTypeMap, cancelStateMap } from '@/config/purchase/offline';

import { pageList, confirmDelivery, confirmFinish, invalid, exportUrl, uploadInvoice, getDownloadInvoiceUrl, relateOrderEdit } from '@/api/purchase/offlineOrder';

export default {
  components: { TableSearch },

  data () {
    const { formatDate, map2Select } = this.$util;

    return {
      deliveryStateMap,
      payStateMap,
      payTypeMap,
      cancelStateMap,
      columns: createTableColumns([
        ['创建时间', 'createTime', { search: { key: 'startTime,endTime', sort: 9 }, formatter: val => formatDate(val) }],
        ['采购单号', 'purchaseNo', { search: { span: 7 } }],
        ['订单总金额（元）', 'totalPrice', { align: 'right' }],
        ['发货状态', 'deliveryState', { search: { ...map2Select(deliveryStateMap), span: 7 } }],
        ['支付状态', 'payState', { search: { ...map2Select(payStateMap), span: 10 } }],
        ['支付方式', 'payType', { search: { ...map2Select(payTypeMap), span: 7 }, formatter: val => payTypeMap[val] }],
        ['作废状态', 'cancelState', { search: { ...map2Select(cancelStateMap), span: 7 } }],
        ['发票', 'invoice'],
        ['关联订单号', 'relateOrderIds', { search: { span: 10 }, formatter: val => val ? val.split(',').join('\n') : '未关联' }],
        ['操作', 'operate'],
      ]),
      selection: [],
      invoice: {
        visible: true,
        currentItem: null,
        uploadLoading: false,
      },
    };
  },

  methods: {
    async getList (pageIndex, pageSize, query) {
      const newQuery = {
        pageIndex,
        pageSize,
        ...query,
      };
      return await pageList(newQuery);
    },

    onSelectionChange (val) {
      this.selection = val;
    },

    checkShowEdit (row) {
      // 发货状态为“待配送或待收货”，支付状态为“待付款或已拒绝”，作废状态为“未作废”下可编辑；

      // 发货状态为“待配送或待收货”
      if ([1, 2].indexOf(row.deliveryState) === -1) {
        return false;
      }

      // 支付状态为“待付款或已拒绝”
      if ([1, 5].indexOf(row.payState) === -1) {
        return false;
      }

      // 作废状态为“未作废”下可编辑；
      if ([1].indexOf(row.cancelState) === -1) {
        return false;
      }

      return true;
    },

    checkShowDelivery (row) {
      // 发货状态为“待配送”，作废状态为“未作废”下可点击“确认发货”；
      return row.deliveryState === 1 && row.cancelState === 1;
    },

    checkShowConfirmFinish (row) {
      // 发货状态为“待收货”，作废状态为“未作废”下可点击“确认完成”；
      return row.deliveryState === 2 && row.cancelState === 1;
    },

    checkShowPay (row) {
      // 支付状态为“待付款或已拒绝”，作废状态为“未作废”下可申请付款；
      return [1, 5].indexOf(row.payState) >= 0 && row.cancelState === 1;
    },

    checkShowInvalid (row) {
      // 支付状态为“待付款或已拒绝”，作废状态为“未作废”下可作废；
      return [1, 5].indexOf(row.payState) >= 0 && row.cancelState === 1;
    },

    checkShowRelateOrder (row) {
      return [3, 4].indexOf(row.payState) === -1 && row.cancelState === 1;
    },

    async onDelivery (row) {
      this.$refs.tableSearch.showLoading();
      try {
        await confirmDelivery(row.purchaseNo);
        this.$refs.tableSearch.reload();
        this.$message.success('确认发货成功');
      } catch (error) {
        this.$refs.tableSearch.hideLoading();
      }
    },

    async onConfirmFinish (row) {
      this.$refs.tableSearch.showLoading();
      try {
        await confirmFinish(row.purchaseNo);
        this.$refs.tableSearch.reload();
        this.$message.success('确认完成成功');
      } catch (error) {
        this.$refs.tableSearch.hideLoading();
      }
    },

    async onInvalid (row) {
      this.$refs.tableSearch.showLoading();
      try {
        await invalid(row.purchaseNo);
        this.$refs.tableSearch.reload();
        this.$message.success('作废采购单成功');
      } catch (error) {
        this.$refs.tableSearch.hideLoading();
      }
    },

    onExport () {
      const purchaseNos = this.selection.map(item => item.purchaseNo).join(',');
      if (!purchaseNos) {
        this.$message.error('请选择要导出的记录');
        return false;
      }
      this.$util.downloadFile(`${exportUrl}?purchaseNos=${purchaseNos}`);
    },

    onViewInvoice (row) {
      this.invoice.currentItem = row;
      this.invoice.visible = true;
    },

    onDownloadInvoice () {
      this.$util.downloadFile(getDownloadInvoiceUrl(this.invoice.currentItem.purchaseNo));
    },

    async uploadInvoice (param) {
      this.invoice.uploadLoading = true;
      try {
        await uploadInvoice(param.file, this.invoice.currentItem.purchaseNo);
        this.invoice.uploadLoading = false;
        this.$message.success('上传成功');
        this.invoice.currentItem.uploadInvoiceTime = Date.now();
      } catch (error) {
        console.error(error);
      }
      this.invoice.uploadLoading = false;
    },

    onRelateOrder (row) {
      this.$prompt('多个订单号之间以英文逗号分隔', '关联订单号', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: row.relateOrderIds || '',
        inputPlaceholder: '请输入关联订单号',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            // instance.confirmButtonText = '关联中...';
            try {
              await relateOrderEdit({
                purchaseNo: row.purchaseNo,
                relateOrderIds: instance.inputValue,
              });
              this.$message.success('关联成功');
              this.$refs.tableSearch.reload();
              done();
            } catch (error) {

            }
            instance.confirmButtonLoading = false;
          } else {
            done();
          }
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
.table-title {
  flex: 1;
  text-align: right;
  margin: -10px 0;
}

.red {
  color: #e30000;
}
.green {
  color: #06b62d;
}

.upload-box {
  margin: auto;
  width: 360px;
  background-color: #fff;
  .btn-box {
    width: 360px;
    display: flex;
    justify-content: space-around;
    margin: 40px 0;
  }
}
.download-box {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  width: 360px;
  height: 180px;
  text-align: center;
  position: relative;
  overflow: hidden;
  line-height: 50px;
  padding: 40px 0;
  .title {
    display: flex;
    align-items: center;
    justify-content: center;
    .icon {
      font-size: 24px;
    }
  }
  .text {
  }
}
</style>
